import sys
import os
import pylab as plt
import numpy as np
from utilities import *
import math
from params import *

data = []
threshold = 3
tracefile = os.path.join(WORKDIR, 'geocascades',
    'cascade_geostats_2days_geometric.txt')

for line in open(tracefile):
    t = map(float,line.split(';'))
    if t[0] >= threshold:
        data.append(t)

sizes = [x[0] for x in data]
depths = [x[1] for x in data]
first_distance = [x[2] for x in data]
seed_locality = [x[3] for x in data]
avg_loc = [x[4] for x in data]
georange = [x[5] for x in data]
geodiv = [x[6] for x in data]
geomed = [x[7] for x in data]
geonear = [x[8] for x in data]
avg_dist = [x[9] for x in data]
duration = [x[10] for x in data]
avg_loc1 = [x[11] for x in data]
avg_loc2 = [x[12] for x in data]
avg_loc3 = [x[13] for x in data]
avg_loc4 = [x[14] for x in data]
seed_followers = [x[15] for x in data]
seed_following = [x[16] for x in data]
georangemed =  [x[17] for x in data]

x,y = log_ecdf(map(lambda i: max(1.0,i), avg_dist),normed=True)
x2,y2 = log_ecdf(map(lambda i: max(1.0,i), georange),normed=True)
x3,y3 = log_ecdf(map(lambda i: max(1.0,i), geodiv),normed=True)
x4,y4 = log_ecdf(map(lambda i: max(1.0,i), geomed),normed=True)
x5,y5 = log_ecdf(map(lambda i: max(1.0,i), geonear),normed=True)
x6,y6 = log_ecdf(map(lambda i: max(1.0,i), georangemed),normed=True)

plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
#plt.semilogx(x,y,'ks')
plt.semilogx(x2,y2,'k-')
plt.semilogx(x3,y3,'k--')
#plt.semilogx(x4,y4,'k*')
#plt.semilogx(x5,y5,'kx')
#plt.legend(['Step distance', 'Georange', 'Geodiversity'],
#        numpoints=1,loc='upper left')
plt.legend(['Georange', 'Geodiversity'],
        numpoints=1,loc='upper left',
        handletextpad=0.1,markerscale=0.66)
plt.xlabel('km')
plt.ylabel('CDF')
plt.grid(True)
plt.savefig('geo_dist_%d.pdf'%threshold)
plt.close()


STEP = 0.05
def roundstep(x):
    return STEP*(int(x/STEP))

def stats(seq):
    if len(seq) == 0:
        return 0.0, 0.0,0.0
    if len(seq) == 1:
        return seq[0], 0.0, seq[0]

    avg = sum(seq)/len(seq)
    avg2 = sum(i**2 for i in seq)/len(seq)
    seq.sort()
    med = seq[len(seq)//2]

    var = avg2 - avg**2
    std = var**0.5

    return avg, std, med

def avgplot(seq1,seq2,num,title,limit):
    values = {}
    for a,b in zip(seq1,seq2):
        if a == -1:
            continue
        i = roundstep(a)
        if not i in values:
            values[i] = []
        values[i].append(b)

    x,y,yerr = [],[],[]
    print ''
    print 'plotting ', num
    for k in sorted(values):
        x.append(k+STEP/2)
        avg,std,med = stats(values[k])
        #y.append(avg)
        y.append(med)
        yerr.append(std)
        print k+STEP/2,avg,med,len(values[k])

    plt.figure()
    plt.clf()
    plt.axes(FIG_AXES2)
    #plt.scatter(scatter_x,scatter_y,alpha=0.3)
    #plt.plot(x,y,'k.-')
    plt.errorbar(x,y,fmt='k.-',yerr=yerr)
    [x1,x2,y1,y2] = plt.axis()
    plt.axis([0,1,0,limit])
    plt.xlabel('Node Locality')
    if title == 'geodiv':
        plt.ylabel('Geodiversity [km]')
    else:
        plt.ylabel('Georange [km]')
    plt.grid(True)
    #plt.ylabel('km')
    plt.savefig('%s_%d.pdf'%(title,num))
    plt.close()

#avgplot(avg_loc,geodiv,0, 'geodiv',8000)
avgplot(avg_loc1,geodiv,1,'geodiv',8000)
avgplot(avg_loc2,geodiv,2,'geodiv',8000)
#avgplot(avg_loc3,geodiv,3,'geodiv',8000)

#avgplot(avg_loc,georange,0, 'georange',4000)
avgplot(avg_loc1,georange,1,'georange',4000)
avgplot(avg_loc2,georange,2,'georange',4000)
#avgplot(avg_loc3,georange,3,'georange',4000)

sys.exit()
values = {}
for a,b in zip(seed_followers,geodiv):
    l = math.log10(a)
    l = float(int(l*10.0))/10
    l = 10**l
    if not l in values:
        values[l] = []
    values[l].append(b)

plt.subplot(111,xscale='log')
x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

plt.errorbar(x,y,yerr=yerr)
plt.xlabel('Seed Indegree')
plt.ylabel('Avg. Geodiversity')
plt.grid(True)
plt.savefig('geodiv_indegree.pdf')
plt.close()

values = {}
for a,b in zip(seed_followers,georange):
    l = math.log10(a)
    l = float(int(l*10.0))/10
    l = 10**l
    if not l in values:
        values[l] = []
    values[l].append(b)

plt.subplot(111,xscale='log')
x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

plt.errorbar(x,y,yerr=yerr)
plt.xlabel('Seed Indegree')
plt.ylabel('Avg. Georange')
plt.grid(True)
plt.savefig('georange_indegree.pdf')
plt.close()

values = {}
for a,b in zip(seed_followers,sizes):
    l = math.log10(a)
    l = float(int(l*10.0))/10
    l = 10**l
    if not l in values:
        values[l] = []
    values[l].append(b)

plt.subplot(111,xscale='log',yscale='log')
x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    print k,avg,std,len(values[k])
    yerr.append(std)

#plt.errorbar(x,y,yerr=yerr)
plt.plot(x,y,'ko-')
plt.xlabel('Seed Indegree')
plt.ylabel('Avg. Cascade size')
plt.grid(True)
plt.savefig('size_indegree.pdf')
plt.close()

values = {}
for a,b in zip(seed_following,sizes):
    if a>0:
        l = math.log10(a)
        l = float(int(l*10.0))/10
        l = 10**l
    else:
        l = 1
    if not l in values:
        values[l] = []
    values[l].append(b)

plt.subplot(111,xscale='log',yscale='log')
x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

#plt.errorbar(x,y,yerr=yerr)
plt.plot(x,y,'ko-')
plt.xlabel('Seed Outdegree')
plt.ylabel('Avg. Cascade size')
plt.grid(True)
plt.savefig('size_outdegree.pdf')
plt.close()


values = {}
for a,b in zip(seed_locality,geodiv):
    i = roundstep(a)
    if not i in values:
        values[i] = []
    values[i].append(b)

x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

plt.errorbar(x,y,yerr=yerr)
[x1,x2,y1,y2] = plt.axis()
plt.axis([0,1,0,y2])
plt.xlabel('Seed locality')
plt.ylabel('Avg. Geodiversity')
plt.savefig('geodiv.pdf')
plt.close()

bins = 10**np.linspace(0,4.5,100)
print max(bins)
def find_bin(x):
    i = 0
    while x > bins[i]:
        i += 1
        if i == len(bins):
            return i-1
    return i

values = {}
for a,b in zip(first_distance,geodiv):
    i = find_bin(a)
    i = bins[i]
    if not i in values:
        values[i] = []
    values[i].append(b)

x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

plt.subplot(111,xscale='log')
plt.errorbar(x,y,yerr=yerr)
plt.xlabel('First step')
plt.ylabel('Avg. Geodiversity')
plt.savefig('geodist.pdf')
plt.close()

values = {}
for a,b in zip(avg_loc,geodiv):
    i = roundstep(a)
    if not i in values:
        values[i] = []
    values[i].append(b)

x,y,yerr = [],[],[]
for k in sorted(values):
    x.append(k)
    avg,std = stats(values[k])
    y.append(avg)
    yerr.append(std)

plt.errorbar(x,y,yerr=yerr)
[x1,x2,y1,y2] = plt.axis()
plt.axis([0,1,0,y2])
plt.xlabel('Avg. locality')
plt.ylabel('Avg. Geodiversity')
plt.savefig('avg_geodiv.pdf')
plt.close()
